package com.tsinghua.server.base.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsinghua.server.common.Result;
import com.tsinghua.server.common.constant.UserConstants;
import com.tsinghua.server.common.utils.BaseUtil;
import com.tsinghua.server.config.jwt.JWTUtils;
import com.tsinghua.server.base.entity.UserEntity;
import com.tsinghua.server.common.exception.BusinessException;
import com.tsinghua.server.base.mapper.UserMapper;
import com.tsinghua.server.base.service.CaptchaService;
import com.tsinghua.server.base.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    private final CaptchaService captchaService;

    @Resource
    UserMapper userMapper;

    @Override
    public String createToken(String username, String password, String verifyKey, String verifyCode) {
        // 验证验证码
        captchaService.valid(verifyKey,verifyCode);

        QueryWrapper<UserEntity> userQuery = new QueryWrapper<>();
        userQuery.eq("username",username);

        UserEntity user = super.getOne(userQuery);

        if (user == null){
            throw new BusinessException("用户名或者密码不正确");
        }

//        if (!(user.getPassword().equals(DigestUtil.md5Hex(password)))){
//            throw new BusinessException("密码不正确");
//        }
        if (!(user.getPassword().equals(password))){
            throw new BusinessException("密码不正确");
        }

        Map<String, String> payload = new HashMap<>();
        payload.put("userName", username);
        payload.put("userId",user.getId().toString());
        return JWTUtils.getToken(payload,7200);
    }

    @Override
    public Result getList(UserEntity user, Integer pageSize, Integer PageNo) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
//        wrapper.setEntity(user);
        if (StringUtils.isNotBlank(user.getUsername())) {
            wrapper.like("username",user.getUsername());
        }
        Page<UserEntity> page = new Page<>(PageNo, pageSize);
        IPage<UserEntity> userPage = userMapper.selectPage(page,wrapper);
        Map retMap = new HashMap();
        retMap.put("total", userPage.getTotal());
        retMap.put("data", userPage.getRecords());

        return Result.succ(retMap);
    }

    @Override
    public Result addUser(UserEntity user) {
        BaseUtil.convertEmptyToNull(user);
        userMapper.insert(user);
        return Result.succ(true);
    }

    @Override
    public String checkUserNameUnique(String userName) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(userName);
        wrapper.setEntity(userEntity);
        int count = userMapper.selectCount(wrapper);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }



    @Override
    public boolean updatePass(Map map, HttpServletRequest request) {
        Long userId = JWTUtils.getUserId(request);

        String newPassword = map.get("newPassword").toString();
        String oldPassword = map.get("oldPassword").toString();
        String confirmPassword = map.get("confirmPassword").toString();

        UserEntity userEntity = super.getById(userId);

        if (!(userEntity.getPassword().equals(DigestUtil.md5Hex(oldPassword)))){
            throw new BusinessException("密码不正确");
        }

        // 更新密码
        if (newPassword.equals(confirmPassword)){
            userEntity.setPassword((DigestUtil.md5Hex(newPassword)));
            super.updateById(userEntity);
            return true;
        }

        return false;
    }

    @Override
    public boolean resetPass(HttpServletRequest request) {
        Long userId = JWTUtils.getUserId(request);
        UserEntity userEntity = super.getById(userId);
        userEntity.setPassword((DigestUtil.md5Hex("111111")));
        return super.updateById(userEntity);
    }

}
